package com.chwn.curiousdiary.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.adapter.FragmentContentAdapter;
import com.chwn.curiousdiary.api.IHomeApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.bean.StoryListBean;
import com.chwn.curiousdiary.bean.VersionBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.CustomEvent;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.service.AudioService;
import com.chwn.curiousdiary.ui.main.fragment.HomeFragment;
import com.chwn.curiousdiary.ui.main.fragment.MineFragment;
import com.chwn.curiousdiary.ui.play.activity.StoryPlayActivity;
import com.chwn.curiousdiary.utils.CustomToast;
import com.chwn.curiousdiary.utils.PopupWindowUtils;
import com.chwn.curiousdiary.utils.UpdateAppUtils;
import com.chwn.curiousdiary.widget.droidflakes.FlakeView;
import com.chwn.harulib.mvp.base.BaseMVPFragment;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.mvp.rx.RxSchedulers;
import com.gyf.barlibrary.ImmersionBar;
import com.nineoldandroids.animation.Animator;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.Observer;

import static com.nineoldandroids.view.ViewPropertyAnimator.animate;

/**
 * desc:
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private ViewPager    mVP;
    private LinearLayout mLLHome;
    private LinearLayout mRLMine;
    private LinearLayout mLLBottom;
    private Toolbar      mToolBar;

    /**
     * 上次点击退出时间
     */
    private long clickTime;
    private int  isFromLook;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        ImmersionBar.with(this)
                .statusBarView(R.id.top_view)
                .statusBarAlpha(0.0f)
                .titleBar(mToolBar, true)
                .addTag("PicAndColor")
                .init();
    }


    private boolean isPlayed;

    /**
     * 暂时取消播放错误回调处理
     * @param event
     */
    public void onEventMainThread(CustomEvent event) {
        switch (event.getState()) {
            case CustomEvent.FROM_LOOK:
                isFromLook = 1;
                break;
            case CustomEvent.MAIN_NOTIFY:
                isPlayed = true;
                break;
        }
    }

    protected void initView() {
        mVP = (ViewPager) findViewById(R.id.vp_content);
        /**
         * 设置最小缓存页面个数
         */
        mVP.setOffscreenPageLimit(2);
        mLLHome = (LinearLayout) findViewById(R.id.ll_home_page);
        mRLMine = (LinearLayout) findViewById(R.id.ll_mine);
        mLLBottom = (LinearLayout) findViewById(R.id.ll_bottom_bar);
        mToolBar = (Toolbar) findViewById(R.id.toolbar);
        findViewById(R.id.ib_enter_play).setOnClickListener(this);
        findViewById(R.id.iv_bottom_play).setOnClickListener(this);
        mLLHome.setTag(0);
        mRLMine.setTag(1);

        ArrayList<BaseMVPFragment> fragments = new ArrayList<>();
        fragments.add(new HomeFragment());

        fragments.add(new MineFragment());

        /**
         * 首页数据立即加载
         */
        fragments.get(0).setLoadDataNow(true);

        mVP.setAdapter(new FragmentContentAdapter(getSupportFragmentManager(), fragments));

        mVP.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                updateBottomIcon(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isFromLook == 1) {
            updateBottomIcon(0);
            setCurrentFragment(0);
        }

        VersionBean versionBean = DiaryApplication.mInstance.versionBean;
        if (versionBean != null && versionBean.getUpdateVersionCode() > DiaryApplication.mInstance.currentVersionCode && DiaryApplication.mInstance.ISFirst) {
            updataAPP(versionBean);
            DiaryApplication.mInstance.ISFirst = false;
        }

        if (storyList == null || user == null) {
            initNewestData();
        }
    }


    private boolean shouldShowDialog() {
        user = DiaryApplication.mInstance.getmUser();
        return user != null && user.getIconNum() != 0 && user.getKeepDay() != 0;
    }


    private PopupWindow mPopWindow;
    private FlakeView   flakeView;
    private ImageView   imgCoin;
    private View        contentView;
    private TextView    iconNum;

    private void showFirstDialog() {
        setAlphaActivity();

        contentView = LayoutInflater.from(this).inflate(R.layout.layout_first_dialog, null);
        mPopWindow = new PopupWindow(contentView,
                RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setContentView(contentView);

        mPopWindow.setOutsideTouchable(true);

        iconNum = (TextView) contentView.findViewById(R.id.tv_icon_num);
        TextView keepDay = (TextView) contentView.findViewById(R.id.tv_keep_day);
        imgCoin = (ImageView) contentView.findViewById(R.id.img_coin);

        LinearLayout container = (LinearLayout) contentView.findViewById(R.id.flake);
        flakeView = new FlakeView(this);
        container.addView(flakeView);

        iconNum.setText("   +" + user.getIconNum());
        keepDay.setText("连续登录" + user.getKeepDay() + "天");

        contentView.findViewById(R.id.iv_login_dialog)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        iconNum.setVisibility(View.GONE);
                        imgCoin.setImageResource(R.drawable.couple_coin);
                        int xValue = contentView.getWidth() - imgCoin.getWidth() * 2;
                        int yValue = contentView.getHeight() - imgCoin.getHeight();
                        animate(imgCoin).scaleX(0.3f).scaleY(0.3f).alpha(0.3f).x(xValue).y(yValue).setStartDelay(200).setDuration(1000);
                        animate(imgCoin).setListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animator) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animator) {
                                flakeView.pause();
                                mPopWindow.dismiss();
                                user.setIconNum(0);
                                DiaryApplication.mInstance.saveUser(user);
                            }

                            @Override
                            public void onAnimationCancel(Animator animator) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animator) {

                            }
                        });

                    }
                });

        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                clearAlphaActivity();
            }
        });

        mPopWindow.setAnimationStyle(PopupWindowUtils.ANIMATION_SET);
        mPopWindow.showAtLocation(mLLBottom, Gravity.FILL, 0, 0);
    }

    private void initNewestData() {
        NetWork.getInstance()
                .getApiService(IHomeApi.class, true)
                .getNewestStoryList(Constant.PAGE_COUNT, DiaryApplication.mInstance.getUserToken(), 1, Constant.OSTYPE)
                .compose(RxSchedulers.<HttpResult<List<StoryListBean>>>io_main())
                .subscribe(homeListObserver);
    }

    /**
     * 最新故事
     */
    private ArrayList<StoryBean> storyList;

    private Observer<HttpResult<List<StoryListBean>>> homeListObserver = new Observer<HttpResult<List<StoryListBean>>>() {

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            if (shouldShowDialog()) {
                showFirstDialog();
            }
        }

        @Override
        public void onNext(HttpResult<List<StoryListBean>> httpResult) {
            if (httpResult.getResult() == 1) {
                List<StoryListBean> data = httpResult.getResdata();

                storyList = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    storyList.add(new StoryBean(data.get(i)));
                }
            }

            if (shouldShowDialog()) {
                showFirstDialog();
            }
        }
    };


    protected void initListener() {
        mLLHome.setOnClickListener(this);
        mRLMine.setOnClickListener(this);
        updateBottomIcon(0);
    }

    private void updateBottomIcon(int position) {
        mLLHome.setSelected(position == 0);
        mRLMine.setSelected(position == 1);
    }

    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.ib_enter_play) {
            enterStoryPlay(-1);

            HashMap<String, String> map = new HashMap<String, String>();
            if (mVP.getCurrentItem() == 0) {
                map.put("type", "首页右上角播放键");
            } else {
                map.put("type", "我的右上角播放键");
            }
            MobclickAgent.onEvent(this, "enter_playpage_way", map);

        } else if (view.getId() == R.id.iv_bottom_play) {
            enterStoryPlay(-1);

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("type", "底部播放键");
            MobclickAgent.onEvent(this, "enter_playpage_way", map);

        } else {
            int position = (Integer) view.getTag();
            setCurrentFragment(position);
            updateBottomIcon(position);
        }
    }

    private void setCurrentFragment(int position) {
        mVP.setCurrentItem(position, false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mVP.getCurrentItem() != 0) {
                mVP.setCurrentItem(0);
            } else {
                if ((System.currentTimeMillis() - clickTime) > 2000) {
                    Toast.makeText(getApplicationContext(), R.string.text_exit_app,
                            Toast.LENGTH_SHORT).show();
                    clickTime = System.currentTimeMillis();
                } else {
                    finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void updataAPP(final VersionBean version) {
        UpdateAppUtils.showUpdateDialog(version, this);
    }


    /**
     * 进入播放界面
     */
    private void enterStoryPlay(int position) {
        if (storyList == null || storyList.size() == 0) {
            CustomToast.showShortToast("请检查网络连接");
            return;
        }

        Intent intent = new Intent(this, StoryPlayActivity.class);
        if (isPlayed) {
            intent.putExtra(Constant.STORY_SERVICE_TYPE, AudioService.FROM_MAIN);
        } else {
            intent.putExtra(Constant.STORY_SERVICE_TYPE, AudioService.NEWEST_ENTER);
            intent.putExtra(Constant.PACKAGE_ID, "-1");
            intent.putExtra("list", storyList);
            intent.putExtra("position", position);
            intent.putExtra("bg_type", 0);

        }
        startActivity(intent);
    }

    private void setAlphaActivity() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.6f;
        getWindow().setAttributes(params);
    }

    private void clearAlphaActivity() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 1f;
        getWindow().setAttributes(params);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (flakeView != null) {
            flakeView.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (flakeView != null) {
            flakeView.resume();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
